package com.woniuxy.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.IOException;
import java.io.InputStream;

/*
@author Jan
@create 2020-06-03 14:21

*/
public class QiniuCloudUtil {
    //设置识别用的各种KEY
    private static final String ACCESS_KEY = "hHHXsRNWOwpMPqivBM5mep4Nob5kVhcDD2JoEkCZ";
    private static final String SECRET_KEY = "c9kVG4JYeKY0-3giP9cgxW3WESbFDrSoKAc_4gXI";
    private static final String BUCKET = "mrjan";

    public static void upload(String fileKey, InputStream fileStream) {
        //提供配置信息,Region.region2(),这儿2是华南区的配置,其他区域自行百度
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);

        Response response = null;
        try {
            //上传
            response = uploadManager.put(fileStream, fileKey, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException e) {
            throw new RuntimeException("上传文件出错", e);
        }
    }

    private static final String CDN_DOMAIN = "http://qbc7j9pld.bkt.clouddn.com/";

    //生成用于全局访问的网络地址，实际应用时可以直接存入数据库
    public static String fullPath(String fileKey) {
        return CDN_DOMAIN + fileKey;
    }

}
